# -*- coding: UTF-8 -*-
import time
import json
import helpers
import urllib2, urllib
from Logs import Logs
from config import config

class MojiApi():

    __moji_lbs_password = config['params']['moji_lbs_password']
    __moji_lbs_token = config['params']['moji_lbs_token']
    __moji_lbs_url = config['params']['moji_lbs_url']

    __moji_global_password = config['params']['moji_global_password']
    __moji_global_token = config['params']['moji_global_token']
    __moji_global_url = config['params']['moji_global_url']

    def __init__(self):
        self.timestamp = str(time.time())
        self.log = Logs()
        pass
  
    def getUrl(self, lat, lon, country_code):
        try:
            if country_code == 'CN':
                md5_str = self.__moji_lbs_password+self.timestamp+lat+lon
                key = helpers.hash_md5(md5_str)
                url = self.__moji_lbs_url + '?timestamp=' +self.timestamp + '&token=' +self.__moji_lbs_token+'&key='+key+'&lat='+lat+'&lon='+lon
            else:
                md5_str = self.__moji_global_password+ self.timestamp+lat+lon
                key = helpers.hash_md5(md5_str)
                url = self.__moji_global_url + '?timestamp=' +self.timestamp + '&token=' +self.__moji_global_token+'&key='+key+'&lat='+lat+'&lon='+lon
            query = urllib2.urlopen(url).read()
            return json.loads(query)

        except Exception, e:
            message = '墨迹天气未知原因执行URL失败！' + '\n Python:' + e.message
            self.log.logwrite(message)
            print message
            #raise e
            return False
        pass
       